import React, {Component} from 'react'
import {Modal, Form, Input, Icon, Button, message} from 'antd'
import {post} from '../common/js/utils'
import {withRouter} from 'react-router-dom'

class Login extends Component {
  state = {
    visible: false,
    closed: false
  }

  componentWillMount() {
    this.props.onRef && this.props.onRef(this)
  }

  handleCancel = () => {
    this.setState({
      visible: false,
      redirect: null
    })
  }

  handleClose = () => {
    this.setState({
      closed: false
    })
  }

  show = (val = null) => {
    this.setState({
      redirect: val
    })
    this.setState({
      visible: true,
      closed: true
    })
  }

  render() {
    return (
      this.state.closed
        ? <Modal
          title="登录"
          visible={this.state.visible}
          footer={null}
          centered
          maskClosable={false}
          destroyOnClose
          onCancel={this.handleCancel}
          afterClose={this.handleClose}
          width={350}
        >
          <WrappedLoginForm redirect={this.state.redirect} {...this.props} />
        </Modal>
        : null
    )
  }
}

const FormItem = Form.Item
class LoginForm extends Component {
  handleSubmit = (e) => {
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.submitForm(values)
      }
    })
  }

  submitForm = async (data) => {
    try {
      let res = await post('/api/users/login', data)
      if (res.result === 1) {
        if (this.props.redirect) {
          this.props.history.replace(this.props.redirect)
        }
        window.location.reload()
      }
    } catch (err) {
      message.error(err.message)
    }
  }

  render() {
    const { getFieldDecorator } = this.props.form
    return (
      <Form onSubmit={this.handleSubmit} className="login-form">
        <FormItem>
          {getFieldDecorator('username', {
            rules: [{
              required: true,
              message: '请输入用户名'
            }, {
              validator(rule, value, callback) {
                if (!value) return callback()
                if (/^[a-zA-Z][a-zA-Z\d_]{5,15}$/.test(value)) {
                  callback()
                } else {
                  callback(new Error('用户名格式不正确'))
                }
              }
            }],
          })(
            <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="请输入用户名" />
          )}
        </FormItem>
        <FormItem>
          {getFieldDecorator('password', {
            rules: [{
              required: true,
              message: '请输入密码'
            }, {
              validator(rule, value, callback) {
                if (!value) return callback()
                if (/^[a-zA-Z\d_]{6,16}$/.test(value)) {
                  callback()
                } else {
                  callback(new Error('密码格式不正确'))
                }
              }
            }],
          })(
            <Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="请输入密码" />
          )}
        </FormItem>
        <FormItem>
          <Button style={{width: '100%'}} type="primary" htmlType="submit" className="login-form-button">登录</Button>
        </FormItem>
      </Form>
    )
  }
}

export const WrappedLoginForm = Form.create()(LoginForm)

export default withRouter(Login)